﻿#include "iostream"
#include "GlobalMsg.h"




//UDP收到数据
void OnUdpReadyRead()
{
    //数据可能同时到达，所以直接需要进行数据判断，知道没有了为止
    while (Server_Udp->hasPendingDatagrams()) {
        QByteArray datagram;
        QHostAddress senderAddress;
        quint16 senderPort;

        datagram.resize(Server_Udp->pendingDatagramSize());
        Server_Udp->readDatagram(datagram.data(), datagram.size(), &senderAddress, &senderPort);

        QByteArray t_data;

        //数据处理
        if(datagram.at(0) == '\0'){ //心跳包
            t_data.append('\0');//心跳返回
            Server_Udp->writeDatagram(t_data,senderAddress,senderPort);
            return;
        }
        else if(datagram.at(0) == '\1'){//UDP通道的验证信息
            int t_retPort = datagram.right(datagram.length() - 1).toInt();//获取返回的TCP端口，也即是唯一ID
            for(int a = 0;a<sizeof(tempList) / sizeof(netConnect);a++){
                if(tempList[a].TcpSocket != nullptr && tempList[a].TcpSocket->peerPort() == t_retPort){//验证成功，加入到常驻列表
                    if(connectList.length() < ConnectMaxNum){ //判断是否为最大连接
                        tempList[a].UDP_Ip = tempList[a].TcpSocket->peerAddress().toString();
                        tempList[a].UDP_Port = senderPort;
                        connectList.append(tempList[a]); //添加到常驻列表
                        std::cout<<"Check success:  IP:" << tempList[a].UDP_Ip.toStdString()<<" TcpPort:" << tempList[a].TcpSocket->peerPort() <<" UdpPort:" << tempList[a].UDP_Port <<std::endl;
                        std::cout<<"User number:" << connectList.length() <<std::endl;

                        QByteArray t_retData;
                        t_retData.append('\2');//返回验证成功信息
                        t_retData.append(QByteArray::number(t_retPort));
                        tempList[a].TcpSocket->write(t_retData); //TCP返回验证成功的消息
                        tempList[a].TcpSocket = nullptr; //制空连接信息
                    }
                    else{
                        //若连接数已达上限
                        std::cout<<"Error: The number of connections has exceeded the upper limit of " << ConnectMaxNum <<std::endl;
                    }
                    break;
                }
            }
            return;
        }




//        QString message = QString::fromUtf8(datagram.constData());
//        qDebug() << "Received message: " << message << " from " << senderAddress.toString() << ":" << senderPort;
    }
}
